import { Toast } from 'antd-mobile';
import React, { useCallback, useEffect, useRef } from 'react';
import { shallowEqual, useSelector } from 'react-redux';

import api from '@/api';
import Dialog from '@/components/Dialog';
import Image from '@/components/Image';
import store from '@/reducers';
import { getUser, getUserProfits, userActions } from '@/reducers/user';
import { guid as myguild, setToken } from '@/utils/common';
import req from '@/utils/req';
import useSetState from '@/utils/useSetState';

import classes from './index.module.less';

type Props = {
  children: React.ReactElement;
  modal?: boolean;
  dataEvent?: string;
  dataModule?: string;
};

const LoginModal: React.FC<Props> = ({ children, modal = true }) => {
  const canCheck = useRef(false);
  const { login, qrCode, guid } = useSelector(
    ({ user }: RootState) => ({
      login: user.login,
      qrCode: user.qrCode,
      guid: user.guid,
    }),
    shallowEqual
  );

  const [{ fetchingQr, open }, setState] = useSetState({
    fetchingQr: false,
    open: false,
  });

  const getQr = useCallback(() => {
    setState({ fetchingQr: true });

    const token = myguild();
    req
      .post<{ url: string }>(api.userGetWxPic, { token: token })
      .then((t) => {
        canCheck.current = true;
        store.dispatch(
          userActions.setState({
            qrCode: t.url,
            guid: token,
          })
        );
        setState({ fetchingQr: false, open: true });
      })
      .then(() => {
        setState({ fetchingQr: false });
      });
  }, [setState]);
  useEffect(() => {
    if (modal === false) {
      getQr();
    }
  }, []);

  const btn = React.cloneElement(children, {
    loading: fetchingQr ? fetchingQr : children.props.loading,
    onClick() {
      if (login) {
        children.props.onClick && children.props.onClick();
      } else {
        getQr();
      }
    },
  });

  useEffect(() => {
    function checkLogin() {
      if (canCheck.current) {
        req
          .post<{ is_login: number; access_token: string }>(api.userCheckWxLogin, {
            token: guid,
            refer: 2,
          })
          .then((data) => {
            if (data.is_login == 0) {
              setTimeout(() => {
                checkLogin();
              }, 1000);
            } else {
              setToken(data.access_token);
              store.dispatch(getUser()).then(() => {
                store.dispatch(getUserProfits());
              });
              setState({ open: false });

              Toast.show({ content: '登录成功' });
            }
          });
      }
    }
    checkLogin();
  }, [guid]);
  useEffect(() => {
    return () => {
      canCheck.current = false;
    };
  }, []);
  return (
    <>
      {btn}
      <Dialog
        className={classes.dwrap}
        show={open}
        onClose={() => {
          canCheck.current = false;
          setState({ open: false });
          if (modal == false) {
            // Taro.switchTab({ url: '/pages/index/index' });
          }
        }}
      >
        <div className={classes.dtitle}>登录</div>
        <div className={classes.dtext}>长按识别二维码关注公众号</div>
        <div className={classes.qrcode}>
          <Image className={classes.qrimg} src={qrCode} />
        </div>
        <div className={classes.agree}>
          <span style={{ color: '#86909C' }}>登录即视为阅读并同意</span>
          <span
            onClick={() => {
              // Taro.navigateTo({ url: '/pages/about/index' });
            }}
          >
            《用户协议》
          </span>
          <span
            onClick={() => {
              // Taro.navigateTo({ url: '/pages/about/index?type=policy' });
            }}
          >
            《隐私政策》
          </span>
        </div>
      </Dialog>
    </>
  );
};

export default LoginModal;
